package controller;

import misc.Configurations;
import misc.Logger;
import misc.Utility;
import misc.Logger.LogType;
import data.DatabaseGateway;

public class RegisterController {
    public static enum RegError{ok,emptyinput,pwdnotequal,
                                    usernametaken,unknown};

    private RegError validateInputs(String username,String pwd1,String pwd2)
    {
        if(username=="" || pwd1=="" || pwd2=="")
            return RegError.emptyinput;

        if(!pwd1.equals(pwd2))
            return RegError.pwdnotequal;

        return RegError.ok;
    }

    private RegError isUsernameAvailable(String username)
    {
        int num=0;

        try
        {
            String query="SELECT * FROM USERS WHERE Username='"+username+"'";
            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                                Configurations.DatabaseName);
            num=gw.executeCount(query);

            if(num!=0)
            {
                gw.closeConnection();
                return RegError.usernametaken;
            }

            gw.closeConnection();
            return RegError.ok;
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),LogType.error);
        }

        return RegError.unknown;
    }

    private RegError createUser(String username,String password)
    {
        try
        {
            String query="INSERT INTO USERS VALUES('"+username+"','"+Utility.
                                                hashMD5(password)+"',now())";
            DatabaseGateway gw = new DatabaseGateway();
            gw.openConnection(Configurations.User,Configurations.Password,
                                                Configurations.DatabaseName);
            int c = gw.executeUpdate(query);
            gw.closeConnection();

            if(c==1)
                return RegError.ok;
            else
                return RegError.unknown;
        }
        catch(Exception e)
        {
            Logger.write(e.getMessage(),LogType.error);
        }

        return RegError.unknown;
    }

    //Single-point domain logic
    public RegError registerThisUser(String username,String pwd1,String pwd2)
    {
        RegError status = null;

        if((status=validateInputs(username,pwd1,pwd2))!=RegError.ok)
            return status;

        if((status = isUsernameAvailable(username))!=RegError.ok)
            return status;

        return createUser(username,pwd1);
    }
}
